package jp.wug.samples;

import com.google.inject.assistedinject.Assisted;
import com.google.inject.servlet.SessionScoped;
import jp.wug.Keys;
import jp.wug.Renderer;

import javax.inject.Inject;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

@SessionScoped
public class Repeat {
    private final Map<String, User> users = new LinkedHashMap<String, User>();

    Repeat() {
        users.put("1", new User("Alice"));
        users.put("2", new User("Bob"));
        users.put("3", new User("Carol"));
    }

    public Map<String, User> getUsers() {
        return Collections.unmodifiableMap(users);
    }

    public void renderUsers(Renderer<String, User> renderer) {
        for (Map.Entry<String, User> entry : users.entrySet()) {
            renderer.render(entry.getKey(), entry.getValue());
        }
    }

    public User getUser(String key) {
        return users.get(key);
    }

    public Keys<String, UserView> getUserKeys() {
        return Keys.create(users.keySet());
    }

    public static class UserView {
        private final User user;

        @Inject
        UserView(Repeat repeat, @Assisted String key) {
            user = repeat.getUser(key);
        }

        public User getUser() {
            return user;
        }
    }

    public static class User {
        private String name;
        private boolean hasGreet;

        User(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public boolean isHasGreet() {
            return hasGreet;
        }

        public void greet() {
            hasGreet = true;
        }
    }
}
